//
//  ConfirmOrderViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/11/2.
//

import UIKit


class ConfirmOrderViewController: BaseViewController {
    var tableView: BaseTableView!
    var confirmBtn: LoaddingButton!  //提交订单按钮
    var orderData: PreviewProductOrderDataModel?  //订单预览data
    var codeExchangeData: CouponDataModel?  //兑换优惠券data
    var couponListData: [CouponDataModel] = []  //优惠券列表data
    var codeExchangeTip: String = ""//兑换优惠券状态提示
    var cartIds: String = ""
    var userData: UserInfoDataModel?  //个人信息data
    var couponType: NSInteger = 0 //默认优惠码
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("confirm_order", comment: "确认订单")
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.view.backgroundColor = Theme.viewBkgGrayColor
        
        let bottomView_height: CGFloat = 54 + IphoneXMarginBottom
        tableView = BaseTableView.init(frame: CGRect.init(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight - bottomView_height), style: .grouped)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.register(ConfirmProductListCell.self, forCellReuseIdentifier: "ConfirmProductListCell")
        tableView.register(ConfirmCouponCell.self, forCellReuseIdentifier: "ConfirmCouponCell")
        tableView.register(ConfirmPriceCell.self, forCellReuseIdentifier: "ConfirmPriceCell")
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = Theme.viewBkgGrayColor
        tableView.separatorStyle = .none
        tableView.delaysContentTouches = true
        self.view.addSubview(tableView)
        
        self.createBottomView()
        self.fetchGetCouponList()
        self.fetchGetInfo()
    }
    
    private func createBottomView(){
        let tempHeight: CGFloat = 54 + IphoneXMarginBottom
        let bottomView = UIView.init(frame: CGRect.init(x: 0, y: kScreenHeight - tempHeight, width: kScreenWidth, height: tempHeight))
        self.view.addSubview(bottomView)
        
        confirmBtn = LoaddingButton.init()
        confirmBtn.setup_titleLabel(text: MMLocalizedString("confirm_submit", comment: "提交订单"))
        confirmBtn.setup_titleColor(color: .white)
        confirmBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        confirmBtn.setBackgroundImage(UIImage.init(color: Theme.mainColor), for: .normal)
        confirmBtn.setBackgroundImage(UIImage.init(color: Theme.mainColorHighLightColor), for: .highlighted)
        confirmBtn.layer.cornerRadius = 8
        confirmBtn.layer.masksToBounds = true
        confirmBtn.addTarget(self, action: #selector(confirmBtnAction), for: .touchUpInside)
        bottomView.addSubview(confirmBtn)
        
        confirmBtn.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.top.equalTo(4)
            make.height.equalTo(46)
        }
    }
    
    ///获取优惠券 useScene：使用场景
    private func fetchGetCouponList(){
        guard self.orderData != nil else {
            return
        }
        let param: [String: String] = [
            "totalAmount": "\(self.orderData?.price ?? 0)",
            "useScene": "1"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.couponCodePageV3(param: param), objectType: CouponListResModel.self) { data in
            let resultObj = data as! CouponListResModel
            if resultObj.code == "1" {
                let tempList = resultObj.data?.content ?? []
                if tempList.count > 0 {
                    tempList.first?.isSelect = true //第一个默认选中
                }
                tempList.forEach({ coupon in
                    coupon.selectBlock = {[weak self] in
                        self?.handleSelectCoupon(coupon: coupon)
                    }
                })
                self.couponListData = tempList
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
            self.tableView.reloadData()
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///勾选优惠券时回调
    private func handleSelectCoupon(coupon: CouponDataModel){
        self.couponListData.forEach { item in
            if item.id != coupon.id {
                item.isSelect = false
            }
        }
        self.tableView.reloadData()
    }
    
    ///获取选中的优惠券
    private func getSelectCouponItem() -> CouponDataModel? {
        let firObj = self.couponListData.first(where: { $0.isSelect })
        return firObj
    }
    
    ///获取用户信息
    private func fetchGetInfo(){
        let param: [String: String] = [:]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.carOrderGetLastInfo(param: param), objectType: UserInfoResModel.self) { data in
            let resultObj = data as! UserInfoResModel
            if resultObj.code == "1" {
                self.userData = resultObj.data
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
            
        }
    }
    
    ///处理兑换
    private func handleInputCodeAction(txt: String){
        self.exchangeCouponByCode(code: txt)
    }
    
    ///兑换优惠券请求 码：JxALpbSo
    private func exchangeCouponByCode(code: String){
        self.view.showLoadingHUDText()
        let param: [String: String] = ["code": code,
                                       "redemptionLocation": "3",
                                       "totalAmount": "\(self.orderData?.price ?? 0)",
                                       "useScene":"1"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.codeExchange(param: param), objectType: CodeExchangeResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! CodeExchangeResModel
            self.codeExchangeTip = ""
            if resultObj.code == "1" {
                self.codeExchangeData = resultObj.data
            }else{
                if resultObj.code != "0" {
                    self.codeExchangeTip = resultObj.msg ?? ""
                }
            }
            self.tableView.reloadData()
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    
    ///提交订单时，判断选的是码还是券
    private func getCouponDescPrice() -> Double {
        var tempPrice: Double = 0
        if let cell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 1)) as? ConfirmCouponCell {
            if cell.selectIndex == 0 {
                //选的是优惠码
                tempPrice = self.codeExchangeData?.reducePrice ?? 0
            }else{
                //选的是优惠券
                let firObj = self.couponListData.first(where: {$0.isSelect == true})
                if firObj != nil {
                    tempPrice = firObj?.reducePrice ?? 0
                }
            }
        }
        return tempPrice
    }
    
    
    ///提交订单
    @objc func confirmBtnAction(){
        self.confirmBtn.showLoading()
        var param: [String: String] = [:]
        param["firstName"] = self.userData?.firstName ?? ""
        param["lastName"] = self.userData?.lastName ?? ""
        param["phone"] = self.userData?.phone ?? ""
        param["email"] = self.userData?.email ?? ""
        param["salutation"] = "\(self.userData?.salutation ?? 0)"  //称谓
        param["cartIds"] = self.cartIds
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.productSubmit(param: param), objectType: ConfirmOrderModel.self) { data in
            self.confirmBtn.handleLoadding()
            let resultObj = data as! ConfirmOrderModel
            if resultObj.code == "1" {
                let tempOrder = OrderContentListModel()
                tempOrder.orderNo = resultObj.data?.orderNo ?? ""
                tempOrder.price = (self.orderData?.price ?? 0) - self.getCouponDescPrice()
                
                let vc = PaymentViewController()
                vc.modalPresentationStyle = .overFullScreen
                vc.orderContentModel = tempOrder
                vc.pushFirstDataBlock = { [weak self] urlStr in
                    let vc = MyWebController()
                    vc.urlStr = urlStr
                    vc.titleStr = MMLocalizedString("confirm_first_pay", comment: "FirstData支付")
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
                self.present(vc, animated: false)
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.confirmBtn.handleLoadding()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
}

extension ConfirmOrderViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2 {
            return IphoneXMarginBottom + 34
        }
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch (indexPath.section, indexPath.row) {
            case (0, _):
                let cell = tableView.dequeueReusableCell(withIdentifier: "ConfirmProductListCell", for: indexPath) as! ConfirmProductListCell
                cell.setConfirmProductListCell(data: self.orderData)
                cell.clipsToBounds = true
                cell.selectionStyle = .none
                return cell
            case (1, _):
                let cell = tableView.dequeueReusableCell(withIdentifier: "ConfirmCouponCell", for: indexPath) as! ConfirmCouponCell
                cell.delegate = self
                cell.couponList = self.couponListData
                cell.setConfirmCouponCell(data: self.codeExchangeData, msg: self.codeExchangeTip)
                cell.clipsToBounds = true
                cell.selectionStyle = .none
                return cell
            case (2, _):
                let cell = tableView.dequeueReusableCell(withIdentifier: "ConfirmPriceCell", for: indexPath) as! ConfirmPriceCell
                cell.orderData = self.orderData
                if self.couponType == 0 {
                    //优惠码
                    cell.reduceData = self.codeExchangeData
                }else{
                    //优惠券
                    cell.reduceData = self.getSelectCouponItem()
                }
                cell.setConfirmPriceCell()
                cell.clipsToBounds = true
                cell.selectionStyle = .none
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
                return cell
        }
    }
}




extension ConfirmOrderViewController: ConfirmCouponCellDelegate {
    /// 切换优惠券/优惠码
    func didChangeCouponCellType(tag: NSInteger) {
        self.couponType = tag
        self.tableView.reloadData()
    }
    /// 输入优惠码监听
    func didChangeCouponCellInputValue(txt: String) {
        self.handleInputCodeAction(txt: txt)
    }
}
